﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Application.Permisos.ServiceAgent;
using System.Windows.Forms;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Permisos
{
	public partial class ExpedicionViewModel
	{
		#region Private properties

		/// <summary>
		/// Sistemas de riego.
		/// </summary>
		private List<RiegoSistema> _riegoSistemas;

		/// <summary>
		/// Sistema de riego seleccionado.s
		/// </summary>
		private RiegoSistema _riegoSistema;

		#endregion

		#region Public properties

		/// <summary>
		/// Sistemas de riego.
		/// </summary>
		public List<RiegoSistema> RiegoSistemas
		{
			get
			{
				return _riegoSistemas;
			}
			private set
			{
				_riegoSistemas = value;
				if (_riegoSistemas != null)
					RaisePropertyChanged("RiegoSistemas");
			}
		}

		/// <summary>
		/// Sistema de riego seleccionado.
		/// </summary>
		public RiegoSistema RiegoSistema
		{
			get
			{
				return _riegoSistema;
			}
			private set
			{
				_riegoSistema = value;
				if (_riegoSistema != null)
					RaisePropertyChanged("RiegoSistema");
			}
		}

		#endregion

		#region Private methods

		private void LoadRiegoSistemas()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					using (PermisosModuleServiceWrapper service = new PermisosModuleServiceWrapper())
					{
						e.Result = service.FindRiegoSistemasByStatus(true);
					}
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						RiegoSistemas = e.Result as List<RiegoSistema>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		private void SetCurrentRiegoSistema(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null && bindingSource.Current != null)
				RiegoSistema = bindingSource.Current as RiegoSistema;
		}

		private void OnRiegoSistemasPropertyChanged()
		{
			_expedicionView.riegoSistemaBindingSource.DataSource = RiegoSistemas;
			_expedicionView.riegoSistemaBindingSource.CurrentChanged += SetCurrentRiegoSistema;
			SetCurrentRiegoSistema(_expedicionView.riegoSistemaBindingSource, new EventArgs());
		}

		private void OnRiegoSistemaPropertyChanged()
		{
			// Actualizar el ID y GUID del sistema de riego
			// al permiso actual.
		}

		#endregion

	}
}
